package org.obm.lmtp.impl;

import java.io.IOException;

import org.obm.mina.Server;
import org.obm.mina.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LmtpServer {
	private static Server<LmtpConfig> lmtpServer;

	private static LmtpConfig config;

	private static final Logger logger = LoggerFactory
			.getLogger(LmtpServer.class);

	public static void startupLmtpServer() throws ServiceException {
		if (lmtpServer != null)
			return;

		config = new LmtpConfig();
		try {
			lmtpServer = new MinaLmtpServer(config);
		} catch (IOException e) {
			logger.error("failed to create MinaLmtpServer", e);
		}
		try {
			lmtpServer.start();
			logger.info("server started");
		} catch (IOException e) {
			logger.error("failed to start LmtpServer", e);
		}

	}

	public static void shutdownLmtpServer() {
		if (lmtpServer != null) {
			lmtpServer.shutdown(10); // TODO shutdown grace period from config
			lmtpServer = null;
		}
	}

	public static LmtpServer getInstance() {
		return (LmtpServer) lmtpServer;
	}

}
